package vn.vfriends.vbox.register;

import vn.vfriends.vbox.provider.GoogleProvider;
import vn.vfriends.vbox.provider.DropBoxProvider;
import vn.vfriends.vbox.provider.StorageProvider;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vbox.model.Provider;
import vn.vfriends.vbox.model.Account;
import vn.vfriends.vbox.model.Storage;
import vn.vfriends.vbox.model.User;
import vn.vfriends.vbox.service.AccountService;
import vn.vfriends.vbox.service.StorageService;

/**
 *
 * @author tuancn
 */
@WebServlet(name = "registerServlet", urlPatterns = {"/register"})
public class RegisterServlet extends HttpServlet {
    
    private static final Logger logger = LoggerFactory.getLogger(RegisterServlet.class);
    
    @Inject
    private AccountService accountService;
    
    @Inject
    private StorageService storageService;
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Account account = new Account();
            
            StorageProvider storageProvider = null;
            
            Provider provider = Provider.valueOf(req.getParameter("provider"));
            account.setProvider(provider);
            
            if(provider == Provider.GOOGLE) {
                storageProvider = new GoogleProvider();
            } else if (provider == Provider.DROPBOX) {
                storageProvider = new DropBoxProvider();
            } else {
                throw new Exception("No found provider");
            }
            
            String code = req.getParameter("code");
            if (code != null) {
                storageProvider.init(code);
                
                account.setAccessToken(storageProvider.getAccessToken());
                account.setOwnId(storageProvider.getOwnId());
                account.setName(storageProvider.getName());
                account.setRefreshToken(storageProvider.getRefreshToken());
                account.setExpiresIn(storageProvider.getExpiresIn());
                User loggedUser = (User)SecurityUtils.getSubject().getSession().getAttribute("LOGGED_USER");
                
                this.accountService.register(loggedUser.getId(), account);
            }
            
            resp.sendRedirect("home.jsf");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resp.sendRedirect("500.jsf");
        }
    }
}
